package fourfaith.com.ff_sl21_app;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.adapter.MyFragmentPagerAdapter;
import fourfaith.com.ff_sl21_app.fragment.DeviceListFragment;
import fourfaith.com.ff_sl21_app.fragment.DeviceMapFragment;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;

/**
 * 设备管理
 */
public class DeviceActivity extends FragmentActivity implements View.OnClickListener{

    private ArrayList<Fragment> pagerItemList = new ArrayList<>();
    public static ViewPager mTabPager;
    private FragmentManager mFragmentManager;
    private TextView mapTab,listTab;
    private ImageView back,query;
    private static Context ctx;

    private int currIndex = 0;// 当前页卡编号

    /** 分页信息 */
    public static int pageStart = 0;
    private static int pageSize = 10 ;
    public static List<Map<String, Object>> dataList = new ArrayList<>();

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /** 地图是否已加载 */
    public static boolean mapIsLoaded = false;

    public static DeviceListFragment listFragment;
    public static DeviceMapFragment mapFragment;

    /** 查询页面 */
    private static String stateStr = "";
    private LinearLayout complete,cancle,cleanBase;
    private DrawerLayout drawerLayout;
    private static EditText deviceCode,deviceName;
    private Spinner deviceStatus;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device);
        ctx=this;
        initView();
        initFragment();
    }

    public void initView(){

        back = (ImageView) findViewById(R.id.back);
        query = (ImageView) findViewById(R.id.query);
        mTabPager = (ViewPager) findViewById(R.id.vPager);
        mapTab = (TextView) findViewById(R.id.mapMain);
        listTab = (TextView) findViewById(R.id.listMain);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        complete = (LinearLayout) findViewById(R.id.complete);
        cancle = (LinearLayout) findViewById(R.id.cancle);

        deviceCode = (EditText) findViewById(R.id.deviceCode);
        deviceName = (EditText) findViewById(R.id.deviceName);
        deviceStatus = (Spinner) findViewById(R.id.deviceStatus);
        cleanBase = (LinearLayout) findViewById(R.id.cleanBase);

        back.setOnClickListener(this);
        query.setOnClickListener(this);
        complete.setOnClickListener(this);
        cancle.setOnClickListener(this);
        cleanBase.setOnClickListener(this);

        mTabPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mTabPager.setOnPageChangeListener(new MyOnPageChangeListener());
        mapTab.setOnClickListener(this);
        listTab.setOnClickListener(this);
        mFragmentManager = this.getSupportFragmentManager();

        //添加监听，关闭时同时关闭软键盘
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        deviceStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //拿到被选择项的值
                stateStr = (String) deviceStatus.getSelectedItem();
                if(stateStr.equals("在线")){
                    stateStr = "1";
                }else if(stateStr.equals("离线")){
                    stateStr = "0";
                }else{
                    stateStr = "";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.mapMain:
                mTabPager.setCurrentItem(0);
                break;
            case R.id.listMain:
                mTabPager.setCurrentItem(1);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.query:
                drawerLayout.openDrawer(GravityCompat.END);
                break;
            case R.id.complete:
                drawerLayout.closeDrawer(GravityCompat.END);
                cleanData();
                listFragment.showLoadingPage();
                getDeviceRequest();
                break;
            case R.id.cancle:
                drawerLayout.closeDrawer(GravityCompat.END);
                break;
            case R.id.cleanBase:
                deviceStatus.setSelection(0);
                deviceCode.setText("");
                deviceName.setText("");
                break;

        }
    }


    private void initFragment(){
        //获取设备列表
        getDeviceRequest();

        //地图页面
        mapFragment = new DeviceMapFragment();
        //列表页面
        listFragment = new DeviceListFragment();
        pagerItemList.add(mapFragment);
        pagerItemList.add(listFragment);
        MyFragmentPagerAdapter mFragmentPagerAdapter = new MyFragmentPagerAdapter(mFragmentManager, pagerItemList);
        mTabPager.setAdapter(mFragmentPagerAdapter);
    }


    /**
     * 获取设备列表
     */
    public static void getDeviceRequest() {
        String userId = Constants.getUserId();

       // String state="";

        String url = null;
        try {
            url = Constants.deviceList +"?userId=" + userId + "&start="+pageStart + "&limit=" + pageSize+"&stcd="+deviceCode.getText()+
                    "&stnm="+ URLEncoder.encode(deviceName.getText() + "", "utf-8")+"&dsfl="+stateStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestQueue mQueue = RequestQueueSingleton.getInstance(ctx).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {

                        JSONObject dataObj = (JSONObject) responseResult.getData();
                        JSONArray dataArray = dataObj.getJSONArray("list");

                        Map<String, Object> map;
                        if (dataArray != null && dataArray.size() > 0) {
                            for (int i = 0; i < dataArray.size(); i++) {
                                pageStart++;
                                JSONObject model = dataArray.getJSONObject(i);

                                map = new HashMap<>();

                                map.put("deviceStatus", String.valueOf(model.get("dsfl")).equals("1")?R.mipmap.online:R.mipmap.offline);
                                map.put("deviceCode", model.get("stcd"));
                                map.put("deviceName", model.get("stnm"));
                                map.put("deviceTime", model.get("moditime"));
                                map.put("deviceAddress", model.get("stlc"));

                                map.put("deviceCenterCode", model.get("center"));
                                map.put("deviceModel", model.get("modelname"));
                                map.put("devicePhone", model.get("tel"));
                                map.put("deviceCoord", model.get("lgtd") + "," + model.get("lttd"));
                                map.put("deviceLgtd", model.get("lgtd"));
                                map.put("deviceLttd", model.get("lttd"));
                                map.put("deviceSttp", model.get("sttp"));

                                dataList.add(map);
                            }
                        }


                        listFragment.showDataPage();
                        listFragment.initData();
                        listFragment.finishRefreshing();
                        mapFragment.hideDetail();
                        mapFragment.addMarkersToMap();

                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listFragment.finishRefreshing();
                listFragment.showErrorPage();
                if (error.networkResponse == null) {
                    Toast.makeText(ctx, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(ctx, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ctx, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        });
        mQueue.add(jsonRequest);

    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }
        @Override
        public void onPageSelected(int arg0) {
            tabSelectStyle(arg0);
            currIndex = arg0;
        }
    }


    public void tabSelectStyle(int i) {
        switch (i) {
            case 0:
                mapTab.setTextColor(ContextCompat.getColorStateList(this, R.color.blue));
                mapTab.setBackgroundResource(R.drawable.textview);
                listTab.setTextColor(ContextCompat.getColorStateList(this, R.color.tabColor));
                listTab.setBackgroundResource(0);
                break;
            case 1:
                listTab.setTextColor(ContextCompat.getColorStateList(this, R.color.blue));
                listTab.setBackgroundResource(R.drawable.textview);
                mapTab.setTextColor(ContextCompat.getColorStateList(this, R.color.tabColor));
                mapTab.setBackgroundResource(0);
                break;
        }
    }

    /**
     * 清除数据
     */
    public static void cleanData(){
        pageStart = 0;
        dataList.clear();
    }


}
